import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

// 获取qiankun环境下的基础路由
const getBasePath = () => {
  return qiankunWindow.__POWERED_BY_QIANKUN__ ? '/vue-devops' : '/';
};

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/website-tracking'
  },
  {
    path: '/test-api',
    name: 'test-api',
    component: () => import('../views/TestApi.vue'),
    meta: { title: 'API测试' }
  },
  {
    path: '/website-tracking',
    name: 'website-tracking',
    component: () => import('../views/WebsiteTracking/index.vue'),
    meta: { title: '网站跟踪' }
  },
  {
    path: '/settings',
    name: 'settings',
    component: () => import('../views/Settings.vue'),
    meta: { title: '系统设置' }
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // vue-devops不包含登录页面，直接放行所有路由
  // 在qiankun环境中，认证由base应用管理
  
  // 如果访问根路径，重定向到首页
  if (to.path === '/') {
    next('/website-tracking');
    return;
  }
  
  next();
});

// 路由切换时自动设置document.title
router.afterEach((to) => {
  const appName = 'vue-devops';
  const baseTitle = 'DevOps 数据分析平台';
  const pageTitle = (to.meta?.title as string) || String(to.name || '');
  const fullTitle = pageTitle ? `${pageTitle} - ${baseTitle}` : baseTitle;
  
  // 直接设置document.title，这将在独立运行时生效
  document.title = fullTitle;
  
  // 如果在微前端环境中，通知基座应用
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    // 使用自定义事件通知基座应用，实现低耦合通信
    try {
      // 创建自定义事件，包含必要的标题信息
      const titleChangeEvent = new CustomEvent('micro-app-title-change', {
        detail: {
          title: pageTitle,
          fullTitle: fullTitle,
          appName: appName,
          path: to.fullPath
        }
      });
      
      // 在window上派发事件，基座应用可以监听此事件
      window.dispatchEvent(titleChangeEvent);
    } catch (e) {
      console.error('[vue-devops] Failed to dispatch title change event:', e);
    }
  }
});

export default router;
